#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/5/14 16:09
# @Author  : liutianwei
# @File    : FormatRecClass.py
# @Software: PyCharm

import os
import sys
from src.utils import PasrCalcRecrate


class format_rec_class:
    def __init__(self, filepath):
        self.data = None
        if os.path.isfile(filepath):
            self.data = open(filepath,encoding="gbk")
        else:
            print("No cache found! -- [%s]" % filepath)

    """ handle default rec text format, such as (id\thello world) """
    """formatted output type, such as( dict[id] = [val, confidence,rec time cost,audio time,read time])"""

    def default(self):
        recTxtDict = {}  # """ rec text dict """
        old_rectxt = {}
        for line in self.data:
            recValAry = []  # """ 0: val, 1: confidence, 2: rec time cost, 3: audio time, 4: read time"""
            if line.strip().find("\t") > -1:
                line = line.replace("<s>", "").replace("</s>", "")
                if len(line.strip().split("\t")) == 1:
                    print("Text of Rec is Null! -- [%s]" % line.strip())
                    recValAry.append("")
                else:
                    """handle speical charachters"""
                    data, spdata = PasrCalcRecrate.PasrCalcRecrate.special_character_filter(
                        "".join(line.strip().split("\t")[1:len(line.strip().split("\t"))]))
                    if spdata == "[--ERROR_CODE--]":
                        print("[REC] - special characters, please check! -- [%s]" % (line.strip().split("\t")[0]),
                            "LOG_ERRO")
                        sys.exit(-1)
                    elif len(spdata) > 0:
                        print("[REC] - special characters: [%s - %s]" % (line.strip().split("\t")[0], spdata), "LOG_WAIN")

                    recValAry.append(data)
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))

                recTxtDict[line.strip().split("\t")[0]] = recValAry
                old_rectxt[line.strip().split("\t")[0]] = "".join(line.strip().split("\t")[1:len(line.strip().split("\t"))])
                # dbg("%s ( %s )"%(val, line.strip().split("\t")[0]),LOG_INFO)
            else:
                print("Text of Rec is Null! -- [%s]" % line.strip(), "LOG_WAIN")
                recValAry.append("")
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))

                recTxtDict[line.strip()] = recValAry
                old_rectxt[line.strip()] = ""
        self.data.close()
        print("Format rec text [default]!", "LOG_INFO")
        return recTxtDict, old_rectxt

    """handle default rec text format, such as (id\t[hello world(100),hello word(20)]\t0.0\t0.0\t0.0)"""
    """formatted output type, such as( dict[id] = [val, confidence,rec time cost,audio time,read time])"""

    def array(self):
        recTxtDict = {}  # """ rec text dict """
        old_rectxt = {}
        for line in self.data:
            recValAry = []  # """ 0: val, 1: confidence, 2: rec time cost, 3: audio time, 4: read time"""
            if len(line.strip().split("\t")) >= 5:
                recval = ""
                cfdval = 0
                wavid = line.strip().split("\t")[0]
                tmpval = line.strip().split("\t")[1]
                rectval = line.strip().split("\t")[2]
                audtval = line.strip().split("\t")[3]
                reatval = line.strip().split("\t")[4]
                if tmpval.find("),") > -1 and tmpval.find("(") > 0:
                    tmpval = tmpval[1: tmpval.find("),")]
                    recval = tmpval[0: tmpval.find("(")]
                    try:
                        cfdval = int(tmpval[tmpval.find("(") + 1:])
                    except:
                        print("Rec confidence isn't a number!")
                elif tmpval.find(")]") > -1 and tmpval.find("(") > 0:
                    tmpval = tmpval[1:tmpval.find(")]")]
                    recval = tmpval[0: tmpval.find("(")]
                    try:
                        cfdval = int(tmpval[tmpval.find("(") + 1:])
                    except:
                        print("Rec confidence isn't a number!")
                else:
                    recval = ""
                    cfdval = 0
                    print("Text of Rec is Null! -- [%s]" % wavid)
                try:
                    rectval = round(int(rectval), 6)
                    audtval = round(int(audtval), 6)
                    reatval = round(int(reatval), 6)
                except:
                    rectval = round(float(0), 6)
                    audtval = round(float(0), 6)
                    reatval = round(float(0), 6)
                    print("Rec time cost info exception!", "LOG_WAIN")
                """handle speical charachters"""
                data, spdata = PasrCalcRecrate.PasrCalcRecrate.special_character_filter(recval)
                if spdata == "[--ERROR_CODE--]":
                    print("[REC] - special characters, please check! -- [%s]" % (line.strip().split("\t")[0]))
                    sys.exit(-1)
                elif len(spdata) > 0:
                    print("[REC] - special characters: [%s - %s]" % (line.strip().split("\t")[0], spdata))
                # xrecval = " ".join(unicode(data, ENCODING)).encode(ENCODING)
                xrecval = data
                recValAry.append(xrecval)
                recValAry.append(cfdval)
                recValAry.append(rectval)
                recValAry.append(audtval)
                recValAry.append(reatval)

                recTxtDict[wavid] = recValAry
                old_rectxt[wavid] = recval

                # dbg("%s ( %s )\t%f\t%f\t%f\t%d"%(recValAry[0], wavid,rectval,audtval,reatval,cfdval),LOG_INFO)
            else:
                wavid = line.strip().split("\t")[0]
                recValAry.append("")
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recValAry.append(round(float(0), 6))
                recTxtDict[wavid] = recValAry
                old_rectxt[wavid] = ""
                print("Text of Rec is Null! -- [%s]" % line.strip())
        self.data.close()
        print("Format rec text [array]!")
        return recTxtDict, old_rectxt

    def timebord(self):
        self.data.close()
        print("Not support timebord!", "LOG_ERRO")

    def spk(self):
        self.data.close()
        print("Not support spk!", "LOG_ERRO")
